package com.boesch.electroOffice.dataaccess.mapper;

import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import com.boesch.electroOffice.dataaccess.common.IllegalDataAccessException;
import com.boesch.electroOffice.dataaccess.dao.IdentifierDao;
import com.boesch.electroOffice.model.electroOffice.Appointment;
import com.boesch.electroOffice.utils.DateUtils;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;

/**
 * This class mappes the rows from database to a Function object.
 * 
 * @author Ralph Koster
 *
 */
public class AppointmentMapper implements RowMapper<Appointment>, Serializable {

	private static final long serialVersionUID = 773701831944545695L;
	private static final Log log = LogFactoryUtil.getLog(AppointmentMapper.class);

	private IdentifierDao identifierDao;

	public AppointmentMapper(IdentifierDao identifierDao) {
		this.identifierDao = identifierDao;
	}

	/**
	 * Mapps all rows from database to a Function object.
	 * 
	 * @see org.springframework.jdbc.core.RowMapper
	 */
	public Appointment mapRow(ResultSet rs, int rowNum) throws SQLException {
		Appointment appointment = new Appointment();

		try {
			appointment.setId(rs.getInt("Id_pk"));
			appointment.setReportNumber(rs.getString("Reportnumber"));
			appointment.setProjectNumber(rs.getInt("Projectnumber"));
			appointment.setIdCustomerAddress(rs.getInt("IdCustomerAddress"));
			appointment.setIdInvoiceAddress(rs.getInt("IdInvoiceAddress"));
			appointment.setIdObjectAddress(rs.getInt("IdObjectAddress"));
			appointment.setPhoneCustomer(rs.getString("Phonecustomer"));
			appointment.setSubject(rs.getString("Subject"));
			appointment.setDescription(rs.getString("Description"));
			appointment.setEmployer(rs.getString("Employer"));
			appointment.setLrUserId(rs.getLong("LrUserId"));
			appointment.setState(identifierDao.getIdentifierById(rs.getInt("StateIdentifierId")));
			appointment.setRegistrationDate(DateUtils.convertDateToLocalDate(rs.getDate("Registrationdate")));
			appointment.setAppointmentDate(DateUtils.convertTimestampToLocalDateTime(rs.getTimestamp("Appointmentdate")));
			appointment.setCreatedBy(rs.getString("Createdby"));
			appointment.setCreatedAt(DateUtils.convertTimestampToLocalDateTime(rs.getTimestamp("Createdat")));
			appointment.setModifiedBy(rs.getString("Modifiedby"));
			appointment.setModifiedAt(DateUtils.convertTimestampToLocalDateTime(rs.getTimestamp("Modifiedat")));
			appointment.setVersion(rs.getInt("Version"));
		} catch (IllegalDataAccessException e) {
			log.error("Failed to load identifier with id: " + rs.getInt("ToolIdentifierId"), e);
			throw new SQLException("Failed to load identifier!", e);
		}

		return appointment;
	}
}
